<?php
/**
 * 平台管理功能 : 角色创建,设定权限,后台用户管理
 * @var unknown
 */
namespace app\htsoft\controller;

use think\Page;
use think\Verify;
use think\Db;
use think\Session;
use think\Url;
use app\common\controller\Base;

class Admin extends Base
{
    /**
     * 管理员登陆
     */
    public function login()
    {
        is_admin_login() && $this->redirect('htsoft/index/index'); // 登录直接跳转
        $config = model("options")->value("verify_on");
        $project_name = model("options")->where(["id"=>1])->value("project_name");
        if (IS_POST) {
            $param = $this->request->param();
            empty($param['user_login']) && $this->error('请输入账号');
            empty($param['user_pass']) && $this->error('请输入密码');
            if ($config == 1) {
                empty($param['captcha']) && $this->error('请输入验证码');
                !captcha_check($param['captcha']) && $this->error('验证码错误');
            }
            $admin = model('AdminUsers')->where([
                'user_login' => $param['user_login'],
                'user_pass' => md5($param['user_pass'])
            ])->find();
//            dump([$param,md5($param['user_pass']),$admin]);die;

            if ($admin) {
                $admin['user_status'] != 1 && $this->error('账号已禁用');
                // 保存状态
                $auth = [
                    'admin_id' => $admin['id'],
                    'user_login' => $admin['user_login'],
                ];
                session('admin_auth', $auth);

                // 更新信息
                model('AdminUsers')->save([
                    'last_login_time' => time(),
                    'last_login_ip'   => $this->request->ip(),
                ], ['id' => $admin['id']]);
                adminLog("管理员" . $admin['nicename'] . "登录!");
                $this->success('登录成功', url('htsoft/index/index'));
            } else {
                $this->error('账号或密码错误');
            }
        }
        $this->assign("config",$config);
        $this->assign("project_name",$project_name);
        return $this->fetch('login');
    }

    public function captcha()
    {
        // ob_clean();
        $config = [
            // 验证码字符集合
            'codeSet'  => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',
            // 验证码字体大小(px)
            'fontSize' => 16,
            // 是否画混淆曲线
            'useCurve' => true,
            // 验证码图片高度
            'imageH'   => 42,
            // 验证码图片宽度
            'imageW'   => 135,
            // 验证码位数
            'length'   => 4,
            // 验证成功后是否重置
            'reset'    => true,
        ];
        return captcha('', $config);
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        session_unset();
        session_destroy();
        session::clear();
        $this->redirect(Url::build('htsoft/Admin/login'));
    }



    /**
     * 规则管理
     */
    public function rule()
    {
        if (IS_POST) {
            $where = " 1 ";
            $data = I('get.');
            $keyword = $data['keyword'];
            unset($data['keyword']);
            unset($data['page']);
            unset($data['limit']);

            if (isset($keyword[0])) {
                $where .= " and (`name` like '%{$keyword}%' or `title` like '%{$keyword}%') ";
            }

            //如果传递了父级id 且不为 '' 添加条件
            if (isset($data['pid']) && $data['pid'] !== '') {
                $ids = implode($this->get_children_str($data['pid']), ',');
                $where .= " and pid in ({$ids}) ";
            }
            unset($data['pid']);//防止条件组装上pid
            foreach ($data as $k => $v) {
                if (isset($v[0])) {
                    $where .= " and `{$k}`={$v} ";
                }
            }

            extract(I('get.'));
            $list = M('auth_rule')
                ->where($where)
                ->select();
            $ids = array_column($list, 'id');

            //treetable需要id为0的父级
            foreach ($list as &$v) {
                if (!in_array($v['pid'], $ids)) {
                    $v['pid'] = 0;
                }
            }
            /**/
            $count = M('auth_rule')->where($where)->count();
            $list = array_values($list);
            $res = array(
                'code' => 0
            , 'count' => $count
            , 'msg' => ''
            , 'data' => $list
            );
            $this->ajaxReturn($res);
        }
        $list = M('auth_rule')
            ->field('title,id,pid')
            ->where(['status' => 1])
            ->select();
        $list = Data::tree($list, 'title', 'id', 'pid');
        $list = array_values($list);
        $this->assign('list', $list);
        $this->display('auth/rule_index');
    }

    /**
     * 添加规则
     */
    public function add_rule()
    {
        if (IS_AJAX) {
            try {
                parse_str($_POST['para'], $data);
                $data = I('data.', '', C('DEFAULT_FILTER'), $data);
                $data = array_filter($data);
                $data['name'] = strtolower($data['name']);
                $data['is_url'] = $data['is_url'] ? $data['is_url'] : 0;
                $data['type'] = $data['type'] ? $data['type'] : 0;
                $data['status'] = $data['status'] ? $data['status'] : 0;
                if (M('auth_rule')->where(['name' => $data['name']])->count()) {
                    $this->error('存在同名规则');
                }
                M('auth_rule')->add($data) ? $this->success('添加成功') : $this->error(M('auth_rule')->getError());
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
        } elseif (IS_GET) {
            $list = M('auth_rule')
                ->field('title,id,pid')
                ->where(['status' => 1])
                ->select();
            $pid = 0;
            if (!empty(I('get.id'))) {
                $pid = I('get.id');
            }
            $this->assign('pid', $pid);
            $list = Data::tree($list, 'title', 'id', 'pid');
            $list = array_values($list);
            $this->assign('list', $list);
            $this->display('auth/rule_add');
        }
    }

    /**
     * 平台角色管理列表
     * @return Ambigous <\think\mixed, string>
     */
    public function role()
    {
        $nowpage = input('page', 1, 'intval');
        $limits = input('limits', 10, 'intval');
        $count = Db::name("role")->where(["shop_id" => 0])->count();
        $allpage = ceil($count / $limits);
        $allpage = intval($allpage);
        if ($nowpage > $allpage) {
            $nowpage = $allpage;
        }
        $role = Db::name("role")->page($nowpage, $limits)->where(["shop_id" => 0])->order("id")->select();
        $this->assign("role", $role);
        $this->assign('allpage', $allpage);
        $this->assign('limits', $limits);
        $this->assign('nowpage', $nowpage);
        $this->assign('allcount', $count);
        return $this->fetch();
    }

    /**
     * 后台角色创建与编辑
     */
    public function roleaddedit()
    {
        if (IS_POST) {
            $posts = input("post.");
            if (!$posts["name"]) {
                $this->error("请输入角色名!");
            }
            if ($posts['id']) {
                //编辑
                $posts["update_time"] = time();
                $result = Db::name("role")->where(['id' => $posts['id']])->Update($posts);
                if ($result) {
                    adminLog2("编辑后台角色" . $posts['name']);
                    $this->success("编辑角色成功!", Url::build('Admin/role'));
                } else {
                    $this->error("您未做任何改动或系统繁忙提交失败,请重试!");
                }
            } else {
                //添加
                $posts["status"] = 1;
                $posts["create_time"] = time();
                $posts["update_time"] = time();
                $posts["shop_id"] = 0;
                $result = Db::name("role")->insertGetId($posts);
                if ($result) {
                    adminLog2("创建后台角色" . $posts['name']);
                    $this->success("角色创建成功!", Url::build("Admin/role"));
                } else {
                    $this->error("服务器繁忙,请稍后重试!!");
                }
            }
        } else {
            $id = intval(input('id'));
            if ($id) {
                $msg = Db::name('role')->where(['id' => $id, 'shop_id' => 0])->find();
                $this->assign('msg', $msg);
            }
            return $this->fetch();
        }
    }

    /**
     * 授权管理
     */
    public function rolejurisdiction()
    {
        if (IS_POST) {
            $roleid = intval(input("post.roleid"));
            if (!$roleid) {
                $this->error("需要授权的角色不存在！");
            }
            if (is_array($_POST['menuid']) && count($_POST['menuid']) > 0) {
                Db::name("auth_access")->where(array("role_id" => $roleid, 'type' => 'admin_url'))->delete();
                $menu = Db::name("auth_rule")->where(["id" => ['in', $_POST['menuid']]])->column("name");
                if ($menu) {
                    foreach ($menu as $v) {
//    					$name = strtolower($v['app']."/".$v['model']."/".$v['action']);
                        $arr[] = ['role_id' => $roleid, "rule_name" => $v, 'type' => 'admin_url'];
                    }
                    $rst = Db::name("auth_access")->insertAll($arr);
                }
                if ($rst) {
                    $name = Db::name('role')->where(["id" => $roleid, 'shop_id' => 0])->value("name");
                    adminLog2("授权角色" . $name . "操作成功!");
                    $this->success("授权成功！", Url::build("Admin/role"));
                } else {
                    $this->error("服务器繁忙，请稍后重试！");
                }
            } else {
                //当没有数据时，清除当前角色授权
                Db::name("auth_access")->where(["role_id" => $roleid])->delete();
                $this->success("没有接收到数据，已执行清除授权成功！");
            }
        } else {
            //角色ID
            $roleid = intval(input("id"));
            if (!$roleid) {
                $this->error("参数错误！");
            }
            $menu = new \think\Tree();
            $menu->icon = array('│ ', '├─ ', '└─ ');
            $menu->nbsp = '&nbsp;&nbsp;&nbsp;';
            $result = Db::name("auth_rule")->where(['module' => 'Htsoft'])->order(array("listorder" => "ASC"))->select();
            $newmenus = array();
            $priv_data = Db::name("auth_access")->where(["role_id" => $roleid])->column("rule_name");//获取权限表数据
            foreach ($result as $m) {
                $newmenus[$m['id']] = $m;
            }
            foreach ($result as $n => $t) {
                $result[$n]['checked'] = ($this->_is_checked($t, $roleid, $priv_data)) ? ' checked' : '';
                $result[$n]['level'] = $this->_get_level($t['id'], $newmenus);
                $result[$n]['parentid_node'] = ($t['parentid']) ? ' class="child-of-node-' . $t['parentid'] . '"' : '';
            }

            $str = "<tr style='font-size:16px' id='node-\$id' \$parentid_node>
                        <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuid[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$title</td>
	    			    </tr>";
            $menu->init($result);
            $categorys = $menu->get_tree(0, $str);
            $name = Db::name('role')->where(["id" => $roleid])->value("name");
            $this->assign("name", $name);
            $this->assign("categorys", $categorys);
            $this->assign("roleid", $roleid);
            return $this->fetch();
        }
    }

    /**
     * 删除角色
     */
    public function roledelete()
    {
        $id = intval(input("id"));
        if ($id == 1) {
            $this->error("禁止删除管理角色!");
        }
        $result = Db::name("role_user")->where(["role_id" => $id])->count();
        if ($result) {
            $this->error("该角色下还有用户未删除,无法删除!");
        }
        $name = Db::name("role")->where(["id" => $id])->value("name");
        $rst = Db::name("role")->delete($id);
        if ($rst) {
            adminLog2("删除后台角色:" . $name);
            $this->success("删除成功");
        } else {
            $this->error("服务器繁忙,请稍后重试!");
        }
    }

    /**
     * @param $data
     * @param $id
     * @return array
     */
    public function getTreesss($data, $id)
    {
        $tree = [$id];
        foreach ($data as $k => $v) {
            if ($v['parentid'] == $id) {
                $tree [] = $v["id"];
                foreach ($data as $kk => $vv) {
                    if ($vv['parentid'] == $v["id"]) {
                        $tree[] = $vv["id"];
                    }
                }
            }
        }
        return $tree;
    }

    /**
     * 平台管理员列表
     * @return Ambigous <\think\mixed, string>
     */
    public function user()
    {
        $nowpage = input('page', 1, 'intval');
        $limits = input('limits', 10, 'intval');
        $_GET = input();
        $map = array();
        $user_login = input('user_login');
        $role_id = input('role_id');
        $start = input('start');
        $end = input('end');
//        if(session('admin_id')>1){
//            $map["u.id|u.parentid"]=session('admin_id');
//        }
        if ($user_login) {
            $map['u.user_login|u.nicename'] = array("like", "%" . $user_login . "%");
        }
        if ($start) {
            $map['u.last_login_time'] = ['EGT', $start];
            if ($end) {
                $map['u.last_login_time'] = ['between', [$start, $end]];
            }
        } else if ($end) {
            $map['u.last_login_time'] = ['ELT', $end];
        }
        $join = " u.id = o.user_id";
        $join2 = "  r.id = o.role_id";
        $join3 = "  d.id = u.city";
        $parentid = Db::name("admin_users")->where(["id" => session("admin_id")])->value("parentid");
        $msg1 = Db::name("admin_users")->alias("u")->field("u.*,r.id as level")
            ->join(DB_PREFIX . "role_user o", $join, "left")
            ->join(DB_PREFIX . "role r", $join2, "left")
            ->join(DB_PREFIX . "district d", $join3, "left")
            ->page($nowpage, $limits)->field("u.*,r.name,d.name as city")->where($map)->order("u.id desc")->select();
        if (session('admin_id') > 1) {
            $ids = $this->getTreesss($msg1, session('admin_id'));
            $msg = [];
            if ($msg1) {
                foreach ($msg1 as $k2 => $v2) {
                    if (in_array($v2["id"], $ids)) {
                        $msg[] = $v2;
                    }
                }
            }
        } else {
            $msg = $msg1;
        }


        $count = count($msg);
        // 计算总页面
        $allpage = intval(ceil($count / $limits));
        if ($nowpage > $allpage) {
            $nowpage = $allpage;
        }

        $tree = new \think\Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $newmenus = array();
        foreach ($msg as $m) {
            $newmenus[$m['id']] = $m;
        }
        foreach ($msg as $n => $r) {
            $msg[$n]['level'] = $this->_get_level($r['id'], $newmenus);
            if (session('admin_id') <= 1) {
                $msg[$n]['parentid_node'] = ($r['parentid']) ? 'class="child-of-node-' . $r['parentid'] . '"' : '';
            } else {
                $msg[$n]['parentid_node'] = ($r['id'] != session('admin_id')) ? 'class="child-of-node-' . $r['parentid'] . '"' : '';
            }
            $add = "iframe('" . Url::build("admin/useraddedit", ["parentid" => $r['id'], "level" => $r['level']]) . "','添加子代理','580px','450px')";
            $edit = "iframe('" . Url::build("admin/useraddedit", ["id" => $r['id']]) . "','编辑代理','580px','450px')";
            if ($r['id'] > 1) {
                if (session('admin_id') <= 1) {
                    if ($r['level'] == 4) {
                        $msg[$n]['str_manage'] = '<a onclick="' . $edit . '" class="layui-btn layui-btn-danger layui-btn-xs" >编辑代理</a>
	    					 								 <a data-url="' . Url::build('Admin/userreset', ['id' => $r['id']]) . '" data-msg="您确定重置此账户的密码为: 123456 吗?" class="layui-btn layui-btn-normal layui-btn-xs J_list_button">重置密码</a> ';
                    } else {
                        $msg[$n]['str_manage'] = '<a onclick="' . $add . '" class="layui-btn  layui-btn-normal layui-btn-xs">添加子代理</a>
	    													  <a onclick="' . $edit . '" class="layui-btn layui-btn-danger layui-btn-xs" >编辑代理</a>
	    													  <a data-url="' . Url::build('Admin/userreset', ['id' => $r['id']]) . '" data-msg="您确定重置此账户的密码为: 123456 吗?" class="layui-btn layui-btn-normal layui-btn-xs J_list_button">重置密码</a>';
                    }
                } else {
                    if ($r['id'] == session('admin_id')) {
                        if ($r['level'] == 4) {
                            $msg[$n]['str_manage'] = '<a data-url="' . Url::build('Admin/userreset', ['id' => $r['id']]) . '" data-msg="您确定重置此账户的密码为: 123456 吗?" class="layui-btn layui-btn-normal layui-btn-xs J_list_button">重置密码</a> ';
                        } else {
                            $msg[$n]['str_manage'] = '<a onclick="' . $add . '" class="layui-btn  layui-btn-normal layui-btn-xs">添加子代理</a>
	    													 <a data-url="' . Url::build('Admin/userreset', ['id' => $r['id']]) . '" data-msg="您确定重置此账户的密码为: 123456 吗?" class="layui-btn layui-btn-normal layui-btn-xs J_list_button">重置密码</a>';
                        }
                    }else{
                        if ($r['level'] == 4) {
                            $msg[$n]['str_manage'] = '<a onclick="' . $edit . '" class="layui-btn layui-btn-danger layui-btn-xs" >编辑代理</a>
	    					 								 <a data-url="' . Url::build('Admin/userreset', ['id' => $r['id']]) . '" data-msg="您确定重置此账户的密码为: 123456 吗?" class="layui-btn layui-btn-normal layui-btn-xs J_list_button">重置密码</a> ';
                        } else {
                            $msg[$n]['str_manage'] = '<a onclick="' . $add . '" class="layui-btn  layui-btn-normal layui-btn-xs">添加子代理</a>
	    													  <a onclick="' . $edit . '" class="layui-btn layui-btn-danger layui-btn-xs" >编辑代理</a>
	    													  <a data-url="' . Url::build('Admin/userreset', ['id' => $r['id']]) . '" data-msg="您确定重置此账户的密码为: 123456 吗?" class="layui-btn layui-btn-normal layui-btn-xs J_list_button">重置密码</a>';
                        }
                    }
                }
            } else {
                $msg[$n]['str_manage'] = "";
            }

            //显示切换开关
            $url1 = Url::build('Admin/userstatus', ['id' => $r['id']]);
            $id = $r['id'];
            $show0 = "<input type='checkbox' data-action='$url1'  lay-skin='switch' id='$id' lay-filter='category' lay-text='启动|禁用'  title='开关' >";
            $show1 = "<input type='checkbox' data-action='$url1'  lay-skin='switch' id='$id' lay-filter='category' lay-text='启动|禁用'  title='开关'  checked>";
            if ($r['id'] > 1) {
                if ($r['id'] == session('admin_id')) {
                    $msg[$n]['user_status'] = "";
                    $msg[$n]['city'] = $r['city'];
                }else{
                    $msg[$n]['user_status'] = $r['user_status'] ? $show1 : $show0;
                    $msg[$n]['city'] = $r['city'];
                }

            } else {
                $msg[$n]['user_status'] = "";
                $msg[$n]['city'] = "全部";
            }
            $msg[$n]['create_time'] = date('Y年m月d日', $r['create_time']) . "<br>" . date('H:i:s', $r['create_time']);
            $msg[$n]['last_login_time'] = date('Y年m月d日', $r['last_login_time']) . "<br>" . date('H:i:s', $r['last_login_time']);
        }
//        dump($msg);die;
        $tree->init($msg);

        $str = "<tr id='node-\$id' \$parentid_node>
						<td style='padding-left:20px;'>\$name</td>
                        <td style='padding-left:20px;'>\$user_login</td>
						<td style='text-align:left;'>\$nicename</td>
						<td style='text-align:left;'>\$spacer\$city</td>
						<td>\$create_time</td>
						<td>\$last_login_time</td>
						<td>\$user_status</td>
						<td>\$str_manage</td>
					</tr>";
        $categorys = $tree->get_tree($parentid, $str);
//		dump($categorys);die;
        $role = Db::name("role")->where(["shop_id" => 0])->order("id")->column('id,name');
        $this->assign("role", $role);
        $this->assign("msg", $msg);
        $this->assign("categorys", $categorys);
        $this->assign('allpage', $allpage);
        $this->assign('nowpage', $nowpage);
        $this->assign('allcount', $count);
        $this->assign('limits', $limits);
        $this->assign('formget', $_GET);
        return $this->fetch();
    }

    /**
     * 用户状态切换
     */
    public function userstatus()
    {
        $id['id'] = intval(input('id'));
        if ($id['id'] > 1) {
            $status = Db::name("admin_users")->where($id)->value('user_status');
            $name = Db::name("admin_users")->where($id)->value('user_login');
            $arr['user_status'] = abs($status - 1);
            $rst = Db::name("admin_users")->where($id)->update($arr);
            if (!$rst) {
                $this->error("服务器繁忙，请稍后再试！");
            }
            if ($arr["user_status"] == 1) {
                adminLog2("启用管理员： " . $name);
                $this->success("启用管理员：" . $name);
            } else if ($arr["user_status"] == 0) {
                adminLog2("禁用管理员：" . $name);
                $this->success("禁用管理员：" . $name);
            }
        }
    }
    /**
     * 用户添加
     */
    public function useradd()
    {
        if (IS_POST) {
            $posts = input("post.");
            if (!$posts['nicename']) {
                $this->error("请填写必填的用户名称!");
            }
            if ($posts['user_pass'] != $posts['checkpwd']) {
                $this->error("两次密码不一致!");
            }
            unset($posts['checkpwd']);
            $user['user_login'] = $posts['user_login'];
            $ret = Db::name("admin_users")->where($user)->find();
            if ($ret) {
                $this->error("该登录账户已注册,请更换重试!");
            }
            if ($posts["pid"]) {
                $posts['parentid'] = $posts["pid"];
            }
            $posts['user_pass'] = sp_password($posts["user_pass"]);
            $posts['city'] = $posts["city"];
            $posts["create_time"] = time();
            $posts['user_type'] = 1;
            $result = Db::name("admin_users")->insertGetId($posts);
            if ($result) {
                $arr['user_id'] = $result;
                $arr['role_id'] = $posts['role_id'];
                $rst = Db::name("role_user")->insert($arr);
                if (!$rst) {
                    adminLog2("添加新后台用户" . $posts['user_login']);
                    $this->success("用户创建成功,但绑定角色失败,请在编辑当中重新绑定!", Url::build("Admin/user"));
                }
                adminLog2("添加新后台用户" . $posts['user_login']);
                $this->success("创建成功!", Url::build("Admin/user"));
            } else {
                $this->error("服务器繁忙,请稍后重试!");
            }

        } else {
            $tree = new \think\Tree();
            $results = Db::name("district")->where(["level" => 1, "upid" => 0])->select();
            foreach ($results as $r1) {
                $arrays[] = $r1;
            }
            $str = "<option value='\$id' >\$spacer \$name</option>";
            $tree->init($arrays);
            $select_categorys = $tree->get_tree(0, $str);
            $role = Db::name("role")->where(["shop_id" => 0, "id" => ["gt", 1]])->select();
            $this->assign("data", $select_categorys);
            $this->assign("role", $role);
            return $this->fetch();
        }
    }
    /**
     * 用户信息编辑
     */
    public function useraddedit()
    {
        if (IS_POST) {
            $posts = input("post.");
            if (!$posts['nicename']) {
                $this->error("请填写必填的用户名称!");
            }
            $id = $posts["id"];
            if ($id) {
                $role_id["role_id"] = $posts["role_id"];
                unset($posts["role_id"]);
                $result = Db::name("admin_users")->where(["id" => $id])->update($posts);
                $user_login = Db::name("admin_users")->where(["id" => $id])->value("user_login");
                $find = Db::name("role_user")->where(["user_id" => $id])->find();
                if ($find) {
                    $rolerst = Db::name("role_user")->where(["user_id" => $id])->update($role_id);
                } else {
                    $rolerst = Db::name("role_user")->insert(['user_id' => $id, 'role_id' => $role_id["role_id"]]);
                }
                if ($result !== false && $rolerst !== false) {
                    adminLog2("更改管理员用户" . $user_login . "的信息!");
                    $this->success("编辑用户信息成功!", Url::build("Admin/user"));
                } else {
                    $this->error("您未做任何改动或系统繁忙提交失败,请重试!");
                }
            } else {
                if ($posts['user_pass'] != $posts['checkpwd']) {
                    $this->error("两次密码不一致!");
                }
                unset($posts['checkpwd']);
                $user['user_login'] = $posts['user_login'];
                $ret = Db::name("admin_users")->where($user)->find();
                if ($ret) {
                    $this->error("该登录账户已注册,请更换重试!");
                }
                if($posts["pid"]){
                    $posts['parentid'] =$posts["pid"];
                }
                $posts['user_pass'] = sp_password($posts["user_pass"]);
                $posts['city'] = $posts["city"];
                $posts["create_time"] = time();
                $posts['user_type'] = 1;
                $result = Db::name("admin_users")->insertGetId($posts);
                if ($result) {
                    $arr['user_id'] = $result;
                    $arr['role_id'] = $posts['role_id'];
                    $rst = Db::name("role_user")->insert($arr);
                    if (!$rst) {
                        adminLog2("添加新后台用户" . $posts['user_login']);
                        $this->success("用户创建成功,但绑定角色失败,请在编辑当中重新绑定!", Url::build("Admin/user"));
                    }
                    adminLog2("添加新后台用户" . $posts['user_login']);
                    $this->success("创建成功!", Url::build("Admin/user"));
                } else {
                    $this->error("服务器繁忙,请稍后重试!");
                }

            }
        } else {
            $id = intval(input("id"));
            $parentid = intval(input("parentid"));
            $tree = new \think\Tree();
            $results = Db::name("district")->where(["level" => 1, "upid" => 0])->select();
            foreach ($results as $r1) {
                $arrays[] = $r1;
            }
            $str = "<option value='\$id' >\$spacer \$name</option>";
            $tree->init($arrays);
            $select_categorys = $tree->get_tree(0, $str);
            if ($id) {
                $join = " u.id = o.user_id";
                $join2 = "  r.id = o.role_id";
                $msg = Db::name("admin_users")->alias("u")->join(DB_PREFIX . "role_user o", $join)
                    ->join(DB_PREFIX . "role r", $join2)
                    ->field("u.*,r.name,o.role_id")->where(["u.id" => $id])->find();
                $city_pid = Db::name("district")->where(["id" => $msg["city"]])->value("upid");
                $result = Db::name("district")->where(["level" => $msg["role_id"] - 1, "upid" => $city_pid])->select();
                foreach ($result as $r) {
                    $r['selected'] = $r['id'] == $msg["city"] ? 'selected' : '';
                    $array[] = $r;
                }
                $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
                $tree->init($array);
                $select_categorys = $tree->get_tree(0, $str);
                $level=Db::name("admin_users")->alias("u")->field("u.id,u.nicename")->join("role_user o",$join)->where(["o.role_id"=>$msg["role_id"]-1])->select();
                $this->assign("level", $level);
                $this->assign("msg", $msg);
            } elseif ($parentid) {
                $join = " u.id = o.user_id";
                $join2 = "r.id = o.role_id";
                $msg = Db::name("admin_users")->alias("u")->join(DB_PREFIX . "role_user o", $join)
                    ->join(DB_PREFIX . "role r", $join2)
                    ->field("u.id as pid,u.city,r.name,o.role_id")->where(["u.id" => $parentid])->find();
                $result = Db::name("district")->where(["level" => $msg["role_id"], "upid" => $msg["city"]])->select();

                foreach ($result as $rr) {
                    $rr['selected'] = $rr['id'] == $msg["city"] ? 'selected' : '';
                    $array1[] = $rr;
                }
                $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
                $tree->init($array1);
//                dump([$result,$array1]);die;
                $select_categorys = $tree->get_tree(0, $str);
                $msg["role_id"] = $msg["role_id"] + 1;
                $this->assign("msg", $msg);
            }

            $role = Db::name("role")->where(["shop_id" => 0, "id" => ["gt", 1]])->select();

            $this->assign("data", $select_categorys);
            $this->assign("role", $role);
            return $this->fetch();
        }
    }

    /**
     *
     */
    public function getaddress()
    {
        $level = input("level") - 1 ? input("level") - 1 : false;
        if ($level) {
            $msg = Db::name('district')->where(["level" => $level])->select();
        } else {
            $msg = [["id" => 0, "name" => "全部"]];
        }
        echo json_encode(array("status" => 1, "data" => $msg));
    }

    /**
     * 重置账户密码
     */
    public function userreset()
    {
        $id = intval(input("id"));
        if ($id == 1) {
            $this->error("超级管理员用户不能重置");
        }
        $num = 123456;
        $user_login = Db::name('admin_users')->where(["id" => $id])->value("user_login");
        $user_pass = Db::name('admin_users')->where(["id" => $id])->value("user_pass");
        $pwd['user_pass'] = sp_password($num);
        if ($pwd['user_pass'] == $user_pass) {
            $this->success("已将此用户密码重置为:123465");
        }
        $rst = Db::name('admin_users')->where(["id" => $id])->update($pwd);
        if ($rst) {
            adminLog2("重置管理员：" . $user_login . "的登录密码");
            $this->success("已将此管理员密码重置为:123465");
        } else {
            $this->error("服务器繁忙,请稍后重试!");
        }
    }
    /**
     * 删除后台用户
     */
// 	public function userdelete() {
// 		$id = intval ( input( "id" ) );
// 		if($id == 1){
// 			$this -> error( "超级管理员用户不能删除" );
// 		}
// 		$user_login= Db::name('admin_users') -> where(["id"=>$id]) -> value("user_login");
// 		$rst = Db::name('admin_users') -> delete($id);
// 		if($rst){
// 			Db::name('role_user') -> where(['user_id'=>$id])->delete();
// 			adminLog2("删除管理员：".$user_login);
// 			$this -> success ( "删除成功" );
// 		} else {
// 			$this -> error ( "服务器繁忙,请稍后重试!" );
// 		}
// 	}

    /**
     *  检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param int $roleid 需要检查的角色ID
     */
    private function _is_checked($menu, $roleid, $priv_data)
    {

        $app = $menu['app'];
        $model = $menu['model'];
        $action = $menu['action'];
        $name = strtolower("$app/$model/$action");
        $name = $menu['name'];;
        if ($priv_data) {
            if (in_array($name, $priv_data)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0)
    {

        if ($array[$id]['parentid'] == 0 || empty($array[$array[$id]['parentid']]) || $array[$id]['parentid'] == $id) {
            return $i;
        } else {
            $i++;
            return $this->_get_level($array[$id]['parentid'], $array, $i);
        }
    }

}